package com.sojoys.chess.game.plugin;

import java.util.Scanner;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.sojoys.artifact.constant.ServerStatusEnum;
import com.sojoys.artifact.core.IPlugin;
import com.sojoys.artifact.core.IServer;
import com.sojoys.artifact.manager.ThreadManager;
import com.sojoys.chess.game.db.DbSave;

/**
 * @author : DengYing
 * @CreateDate : 2017年4月21日 下午6:04:27
 * @Description ：后台命令插件
 */
public class CmdPlugin implements IPlugin,Runnable {
	volatile boolean running = false;
	
	@Override
	public boolean start() {
		ThreadPoolTaskExecutor task = ThreadManager.getInstance().getThreadPoolTaskExecutor("taskExecutor");
		task.execute(this);
		return true;
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void run() {
		while (!running) {
			if (IServer.SERVER_STATUS == ServerStatusEnum.RUNNING) {
				running = true;
			}
		}
		while(running){
			System.out.println("cmd> Input \"help\" to get command list" + IServer.SERVER_STATUS); 
			try{ 
				System.out.print("cmd>"); 
				Scanner sc = new Scanner(System.in);
				if(sc.hasNextLine()){
					try {
						final String cmd  = sc.nextLine();
						processCmd(cmd);
					} catch (Exception e) {
						e.printStackTrace();
						System.out.println("继续,别输入ctrl + z");
					}
				}
				
			}catch (Exception e) {
				e.printStackTrace();
				System.out.println("cmd error ....");
			}
		}
	}

	public void processCmd(String cmd) throws Exception {
		if (cmd == null)
			return;
		if(cmd.equals("stop")){
			IServer.SERVER_STATUS = ServerStatusEnum.STOPPING;
			running = false;
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					IServer.stop();
				}
			});
			t.start();
		}else if(cmd.equals("dbsave")){
			DbSave.saveAll();
			System.out.println("----------save database succeed");
		}else if(cmd.equals("refuseService")){
			IServer.SERVER_STATUS = ServerStatusEnum.REFUSE_SERVICE;
			System.out.println("Server Status -> " + IServer.SERVER_STATUS );
		}
	}
}
